﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Salon
{
    public partial class FormOrder : Form
    {
        private Order EditingOrder;
        private double last_cost_value = 0.0;
        private double last_price_value = 0.0;
        private double last_disc_price_value = 0.0; // cena z rabatem
        private double last_discount_value = 0.0;
        private bool event_enabled = true;
        private IList<Car> cars_list;

        public FormOrder()
        {
            EditingOrder = new Order();
            InitializeFormOrder();
        }
        public FormOrder(Order order)
        {
            if (order == null) EditingOrder = new Order();
            else               EditingOrder = order;
            InitializeFormOrder();
        }
        private void fillFields(Order order)
        {

            if (order == null) return;

            EditingOrder = order;
            
            txtId.Text = order.Id.ToString();
            if (order.Client != null) txtClientID.Text = order.Client.Id.ToString();
            cmbAutoSalon.SelectedValue = order.SalonId;

            txtCost.Text = order.Cost.ToString();
            txtPrice.Text = order.EndPrice.ToString();
            txtDiscPrice.Text = order.Price.ToString();


            // -------- Lista samochodów ------- //

            IList<Car> Cars = ServiceFactory.getCarService().getCarsByOrderId( EditingOrder.Id ); 

            foreach ( Car car in Cars )
            {
                lblCarInfo.Text = car.Id.ToString();

                cars_list.Add(car);

                lstbCars.SelectedItem = null;
                lstbCars.DataSource = null;
                lstbCars.ValueMember = "Id";
                lstbCars.DisplayMember = "";
                lstbCars.DataSource = cars_list;

                CalculatePrice();
            }
        }

        private void InitializeFormOrder()
        {
            cars_list = new List<Car>();

            InitializeComponent();
            
            lstbCars.DataSource = null;
            cmbAutoSalon.Initialize();
            
            txtPrice.Text = txtDiscPrice.Text = txtDiscount.Text = "0";
            last_price_value = 0.0;
            last_disc_price_value = 0.0;
            last_discount_value = 0.0;

            txtUserID.Text = Global.currentUser.Id.ToString();
            cmbAutoSalon.SelectedValue = Global.currentUser.Salon.Id;

            this.dtpOrderDate.Enabled = true;
            this.dtpPayDate.Enabled = false;
            this.dtpEndDate.Enabled = false;
        }


        private void FormOrder_Load(object sender, EventArgs e)
        {
            refreshStatus();
            fillFields(EditingOrder);
        }

        private void txtPrice_TextChanged(object sender, EventArgs e)
        {
            if (event_enabled)
            {
                event_enabled = false;
                try
                {
                    if (txtPrice.Text == "-") txtPrice.Text = "0";
                    if (txtPrice.Text == "") txtPrice.Text = "0";
                    double cost = Convert.ToDouble(txtPrice.Text.Replace('.', ','));
                    last_price_value = cost;
                    last_disc_price_value = last_price_value - last_discount_value;
                    txtDiscPrice.Text = last_disc_price_value.ToString();

                    if (last_price_value != 0.0)
                        lblRabat.Text = (last_discount_value * 100.0 / last_price_value).ToString() + " %";
                }
                catch (Exception)
                {
                    txtPrice.Text = last_price_value.ToString();

                    //lblClientInfo.Text = last_price_value.ToString() + "Error!";
                }
                event_enabled = true;
            }
        }

        private void txtDiscPrice_TextChanged(object sender, EventArgs e)
        {
            if (event_enabled)
            {
                event_enabled = false;
                try
                {
                    if (txtDiscPrice.Text == "-") txtDiscPrice.Text = "0";
                    if (txtDiscPrice.Text == "") txtDiscPrice.Text = "0";
                    double price = Convert.ToDouble(txtDiscPrice.Text.Replace('.', ','));
                    last_disc_price_value = price;
                    last_discount_value = last_price_value-price;
                    txtDiscount.Text = last_discount_value.ToString();

                    if (last_price_value != 0.0)
                        lblRabat.Text = (last_discount_value * 100.0 / last_price_value).ToString() + " %";
                }
                catch (Exception)
                {
                    txtDiscPrice.Text = last_disc_price_value.ToString();
                }
                event_enabled = true;
            }
        }

        private void txtDiscount_TextChanged(object sender, EventArgs e)
        {
            if (event_enabled)
            {
                event_enabled = false;
                try
                {
                    if (txtDiscount.Text == "") txtDiscount.Text = "0";
                    if (txtDiscount.Text == "-") txtDiscount.Text = "0";
                    double discount = Convert.ToDouble(txtDiscount.Text.Replace('.', ','));
                    last_discount_value = discount;
                    last_disc_price_value = last_price_value - discount;
                    txtDiscPrice.Text = last_disc_price_value.ToString();

                    if (last_price_value != 0.0)
                    {
                        lblRabat.Text = (last_discount_value * 100.0 / last_price_value).ToString() + " %";
                        txtDiscountP.Text = (last_discount_value * 100.0 / last_price_value).ToString() ;
                    }
                }
                catch (Exception)
                {
                    txtDiscount.Text = last_discount_value.ToString();
                }
                event_enabled = true;
            }
        }
        private void txtDiscountP_TextChanged(object sender, EventArgs e)
        {
            
            try
            {
                if (txtDiscountP.Text == "") txtDiscountP.Text = "0";
                if (txtDiscountP.Text == "-") txtDiscountP.Text = "0";
                double discountP = Convert.ToDouble(txtDiscountP.Text.Replace('.', ','));
                last_discount_value = last_price_value * discountP * 0.01;
                txtDiscount.Text = last_discount_value.ToString();
            }
            catch (Exception)
            {
                //txtDiscount.Text = last_discount_value.ToString();
            }
        }


        private void txtClientID_TextChanged(object sender, EventArgs e)
        {

            try
            {
                if (txtDiscount.Text == "") txtDiscount.Text = "0";
                int cid = Convert.ToInt32(txtClientID.Text);

                Client client = ServiceFactory.getClientService().getClientById(cid);

                if (client != null)
                {
                    lblClientInfo.Text = client.Name + "\nul. ";
                    lblClientInfo.Text += client.Street + " ";
                    lblClientInfo.Text += client.FlatNumber + "\n";
                    lblClientInfo.Text += client.City + " (";
                    lblClientInfo.Text += client.Zip + ")\n";
                    lblClientInfo.Text += client.Country + "\n";
                }
            }
            catch (Exception) { }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnSetClient_Click(object sender, EventArgs e)
        {
            if (EditingOrder.Id == 0)
            {
                RegisterClients regcli = new RegisterClients(true);
                regcli.ShowDialog();
                if (regcli.ChosenClient != null)
                {
                    //EditingOrder.Client.Id = 
                    
                    txtClientID.Text = regcli.ChosenClient.Id.ToString();

                    // ? txtSalonSend.Text = transfer.Car.Salon.Name;
                }
            }
        }

        private void btnAddCar_Click(object sender, EventArgs e)
        {
            RegisterCars regcar = new RegisterCars(true);
            regcar.ShowDialog();
            if (regcar.ChosenCar != null)
            {
                // dodje samochody tylko na zapisanym zamówieniu:
                if (EditingOrder.Id < 1) // jeśli nie ma id
                {
                    MessageBox.Show("Zamówienie musi być zapisane przed dodaniem samocgodu!","Error");
                    return;
                }

                int id = regcar.ChosenCar.Id;
                Car car = ServiceFactory.getCarService().getCarById(id);
                lblCarInfo.Text = id.ToString();

                //cars_list = ServiceFactory.getCarService().getCarsByOrderId(1);
                cars_list.Add( car );

                lstbCars.SelectedItem = null;
                lstbCars.DataSource = null;
                lstbCars.ValueMember = "Id";
                lstbCars.DisplayMember = "";
                lstbCars.DataSource = cars_list;

                //ServiceFactory.getCarService().setActive(id, false);
                ServiceFactory.getCarService().addToOrder( car, EditingOrder.Id ); // <- tu musi być id zamówienia!

                CalculatePrice();
            }
        }
        private void btnDelCar_Click(object sender, EventArgs e)
        {
            //ServiceFactory.getCarService().setActive( (int) lstbCars.SelectedValue, true);
            ServiceFactory.getCarService().removeFromOrder( lstbCars.SelectedItem as Car );
            cars_list.Remove( lstbCars.SelectedItem as Car );

            lstbCars.SelectedItem = null;
            lstbCars.DataSource = null;
            lstbCars.ValueMember = "Id";
            lstbCars.DisplayMember = "";
            lstbCars.DataSource = cars_list;

            CalculatePrice();
        }

        private void lstbCars_SelectedIndexChanged(object sender, EventArgs e)
        {
            Car car = lstbCars.SelectedItem as Car;
            if (car != null)
            {
                lblCarInfo.Text =  car.ToString();
                lblCarInfo.Text += "\nKoszt: " + car.Cost.ToString();
                lblCarInfo.Text += "\nCena: " + car.Price.ToString();
                lblCarInfo.Text += "\nRabat: " + car.Discount.ToString();

                // Opcje

                //IList<CarOptionItem> lista_elem = new List<CarOptionItem>();

                IList<CarOptionItem> lista_elem = ServiceFactory.getDictService().getCarOptions(car.Id);

                while (clbOptions.Items.Count>0) clbOptions.Items.RemoveAt(0);
                foreach (CarOptionItem coi in lista_elem)
                {
                    clbOptions.Items.Add(coi, coi.State == CarOptionItem.EnumState.Available);
                }
            }
        }

        private void CalculatePrice()
        {
            
                // Aktualizacja cen:

                last_cost_value = 0.0;
                last_price_value = 0.0;
                last_discount_value = 0.0;
                foreach (Car car in cars_list)
                {
                    last_cost_value += car.Cost;
                    last_price_value += car.Price;
                    last_discount_value += car.Discount;
                }

                txtCost.Text = last_cost_value.ToString();
                txtPrice.Text = last_price_value.ToString();
                txtDiscount.Text = last_discount_value.ToString();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            /*if (cars_list.Count < 1)
            {
                MessageBox.Show("Przed zapisaniem należy wybrać przynajmniej jeden samochód!","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }*/
            if (txtClientID.Text == "")
            {
                MessageBox.Show("Przed zapisaniem należy wybrać klienta!","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            //==- ZAPIS -==//

            // Blokada edycji po zatwierdzeniu
            if (EditingOrder.State < 1)
            {
                EditingOrder.Salesman = Global.currentUser;
                EditingOrder.Client = ServiceFactory.getClientService().getClientById(Convert.ToInt32(txtClientID.Text));
                EditingOrder.SalonId = Global.currentUser.Salon.Id;

                EditingOrder.Price = (decimal)last_price_value;
                EditingOrder.EndPrice = (decimal)last_disc_price_value;
                EditingOrder.Cost = (decimal)last_cost_value;
            }
            EditingOrder.OrderDate = dtpOrderDate.Value; // ??
            EditingOrder.PayDate = dtpPayDate.Value;
            EditingOrder.EndDate = dtpEndDate.Value;

            if (EditingOrder.Id > 1)
            {
                ServiceFactory.getOrderService().saveOrder(EditingOrder);
            }
            else
            {
                EditingOrder = ServiceFactory.getOrderService().saveOrder(EditingOrder);
                txtId.Text = EditingOrder.Id.ToString();
            }

            refreshStatus();
        }

        private void refreshStatus()
        {
            if (EditingOrder.State > 0) // Blokada edycji po zatwierdzeniu
            {
                txtCost.ReadOnly = txtDiscPrice.ReadOnly = txtDiscount.ReadOnly = txtPrice.ReadOnly = true;
                btnAddCar.Enabled = btnDelCar.Enabled = btnSetClient.Enabled = false;
            }

            if (EditingOrder.Id < 1)
            {
                // Status nieaktywny
                lblStatus.Text = "Nie zapisane";
                btnState.Enabled = false;
                btnState.Text = "";
                dtpOrderDate.Enabled = false;
                dtpPayDate.Enabled = false;
                dtpEndDate.Enabled = false;

                // blokada dodawania samochodów przed zapisaniem
                btnAddCar.Enabled = btnDelCar.Enabled = false;
            }
            else
            {
                // Status
                if (EditingOrder.State == 0) // Nowe:
                {
                    lblStatus.Text = "Nowe";
                    btnState.Enabled = true;
                    btnState.Text = "Zatwierdź";
                    dtpOrderDate.Enabled = true;
                    dtpPayDate.Enabled = false;
                    dtpEndDate.Enabled = false;

                    btnAddCar.Enabled = btnDelCar.Enabled = true;
                }
                else
                if (EditingOrder.State == 1) // Zatwierdzone:
                {
                    lblStatus.Text = "Zatwierdzone";
                    btnState.Enabled = true;
                    btnState.Text = "Zapłacone";
                    dtpOrderDate.Enabled = false;
                    dtpPayDate.Enabled = true;
                    dtpEndDate.Enabled = false;
                }
                else
                if (EditingOrder.State == 2) // Zapłacone:
                {
                    lblStatus.Text = "Zapłacone";
                    btnState.Enabled = true;
                    btnState.Text = "Zrealizowane";
                    dtpOrderDate.Enabled = false;
                    dtpPayDate.Enabled = false;
                    dtpEndDate.Enabled = true;
                }
                else
                if (EditingOrder.State == 3) // Zrealizowane:
                {
                    lblStatus.Text = "Zrealizowane";
                    btnState.Enabled = false;
                    btnState.Text = "";
                    dtpOrderDate.Enabled = false;
                    dtpPayDate.Enabled = false;
                    dtpEndDate.Enabled = false;
                }
            }
        }

        private void btnState_Click(object sender, EventArgs e)
        {
            switch (EditingOrder.State)
            {
                case 0: // Nowe:
                    EditingOrder.State = 1;
                    break;

                case 1: // Zatwierdzone:
                    EditingOrder.State = 2;
                    break;

                case 2: // Zapłacone:
                    EditingOrder.State = 3;
                    break;

                case 3: // Zrealizowane:
                    break;
            }

            btnSave_Click(null, null);
            refreshStatus();
        }

    }
}
